package com.pentajock.docdb.utils;

import com.pentajock.docdb.Main;
import com.pentajock.docdb.dialogs.Dialogs;
import com.pentajock.docdb.lang.Lang;

/*
 * Liscense: 	GPL http://www.gnu.org/copyleft/gpl.html
 * By: 		A. Tres Finocchiaro
 * Date:	2007
 * Java:	6.0SE
 */
 
 /*
  * A class for creating desktop icons that point to a Java jar
  * requires QuickIni
  *
  * Note, if your sourcepath differes from your Jar path, you may find the
  * shortcut pointing to an invalid location.  This is normal, and should
  * work fine once you've jarred your project
  *
  */

public class DesktopIconFactory {
	public enum OS {
		WINDOWS ("windows"),
		LINUX ("linux"),
		BSD ("bsd"),
		SOLARIS ("solaris"),
		OSX ("mac os x"),
		UNKNOWN ("uknown");
		
		String osName;
		String fullName;
		OS(String osName) {
			this.osName = osName.toLowerCase().replace(" ", "_");
			this.fullName = getOSName();
		}
		
		public String getName() {
			return osName;
		}
		
		public String getFullName() {
			return fullName;
		}
		
		public String getIconExtension() {
			switch(this) {
				case WINDOWS: return "ico";
				case LINUX: return "png";
				/* Below Operating Systems have not been tested and may not work */
				case BSD: return "png";
				case SOLARIS: return "png";
				default: return "png";
			}
		}
		
		public String getShortcutExtension() {
			switch(this) {
				case WINDOWS: return "URL";
				case LINUX: return "desktop";
				/* Below Operating Systems have not been tested and may not work */
				case BSD: return "desktop";
				case SOLARIS: return "desktop";
				default: return "desktop";
			}
		}
		
		public static OS getOS() {
			for (OS o : values()) {
				if (getOSName().startsWith(o.getName())) {
					return o;
				}
			}
			return UNKNOWN;
		}
		
		private static String getOSName() {
			return System.getProperty("os.name").toLowerCase().replace(" ", "_");
		}
	}
	
	/*
	 * Can be specified in with constructor
	 */
	private String imageFolder;
	private String iconName;
	private String jarName;
	private String workingPath;
	private String desktopPath;
	
	/*
	 * Always auto-generated with constuctor
	 */
	private String shortcutPath;
	private String jarPath;
	private String iconResource;
	private String iconPath;  
	private OS thisOS;
	
	private DesktopIconFactory() {
		constructorHelper(".images/", 
			//"Document Database",
			Lang.MISC.getText("TITLE", "Document Database"), //Modified
			System.getProperty("user.dir") + "/", 
			System.getProperty("user.home").toLowerCase() + "/Desktop/", 
			"DBClient.jar");
	}
	
	private DesktopIconFactory(String imageFolder, String iconName, String jarName) {
		constructorHelper(imageFolder, 
			iconName, 
			System.getProperty("user.dir") + "/", 
			System.getProperty("user.home").toLowerCase() + "/Desktop/", 
			jarName);
	}
	
	private DesktopIconFactory(String imageFolder, String iconName, String workingPath, String desktopPath, String jarName) {
		constructorHelper(imageFolder, iconName, workingPath, desktopPath, jarName);
	}
	
	private void constructorHelper(String imageFolder, String iconName, String workingPath, String desktopPath, String jarName) {
		setOS();
		this.imageFolder = appendSlash(imageFolder);
		this.iconName = iconName;
		this.workingPath = appendSlash(workingPath);
		this.desktopPath = appendSlash(desktopPath);
		this.jarName = jarName;
		this.shortcutPath = this.desktopPath + this.iconName + "." + thisOS.getShortcutExtension(); 
		this.jarPath = this.workingPath + this.jarName;
		
		String osName;
		if (thisOS == OS.WINDOWS)
			osName = thisOS.getFullName();
		else
			osName = thisOS.getName();
		
		this.iconResource = this.imageFolder + osName + "." + thisOS.getIconExtension();
		this.iconPath = System.getProperty("user.home").toLowerCase() + 
			"/." + Main.DEFAULT_TITLE + "/" + osName + "." + thisOS.getIconExtension();
	}
	
	private String appendSlash(String s) {
		return (s == null || (s.endsWith("/") || s.endsWith("\\"))) ? s : s + "/";
	}
	
	private void setOS() {
		thisOS = OS.getOS();
	}
	
	public OS getOS() {
		return thisOS;
	}
	
	public String getIconResource() {
		return iconResource;
	}
	
	public String getIconPath() {
		return iconPath;
	}
	
	public String getShortcutPath() {
		return shortcutPath;
	}
	
	public String getJarPath() {
		return jarPath;
	}
	
	public String getWorkingPath() {
		return workingPath;
	}
	
	public String getIconName() {
		return iconName;
	}
	
	/* 
	 * Creates a desktop shortcut to (dbclient.jar) file.  Another.
	 * elaborate hack, since each OS has a different method of
	 * doing this. OSX will not work without some coding
	 * Linux/Solaris/BSD/Windows should work just fine, since they
	 * have similar Desktop locations and shortcut formats.
	 */
	public static boolean createDesktopIcon(String imageFolder, String iconName, String jarName) {
		return createDesktopIcon(imageFolder, 
			iconName, 
			System.getProperty("user.dir") + "/", 
			System.getProperty("user.home").toLowerCase() + "/Desktop/", 
			jarName);
	}	
	
	public static boolean createDesktopIcon(String imageFolder, String iconName, String workingPath, String desktopPath, String jarName) {
		if (System.getProperty("user.dir").toLowerCase().contains("source"))
			if (!Dialogs.showConfirm(Lang.DIALOG.get("DESKTOP_ICON_WARNING", 
				"Shortcuts to source folder are not recommended.  Continue?")))
					return false;
		DesktopIconFactory d = new DesktopIconFactory(imageFolder, iconName, workingPath, desktopPath, jarName);
		QuickIni desktopIcon = new QuickIni(d.getShortcutPath()); 		// Modified
		//QuickIni desktopIcon = new QuickIni(d.getShortCutPath());
		Utils.copyFromJar(d.getIconResource(),d.getIconPath()); 	// Modified
		//copyFromJar(d.getIconResource(),d.getIconPath());
		switch(d.getOS()) {
			case WINDOWS: 
				desktopIcon.setStringProperty("InternetShortcut", "URL", d.getJarPath());
				desktopIcon.setStringProperty("InternetShortcut", "WorkingDirectory", d.getWorkingPath());
				desktopIcon.setStringProperty("InternetShortcut", "IconIndex", "0");
				desktopIcon.setStringProperty("InternetShortcut", "IconFile", d.getIconPath());
				break;
			case SOLARIS: 	// Move Down
			case BSD: 	// Move Down
			case LINUX: 
				desktopIcon.setStringProperty("Desktop Entry", "Name", d.getIconName());
				desktopIcon.setStringProperty("Desktop Entry", "Comment[en_US]", "Search and update procedures & documentation.");
				desktopIcon.setStringProperty("Desktop Entry", "Exec", "java -jar \"" + d.getJarPath() + "\"");
				desktopIcon.setStringProperty("Desktop Entry", "GenericName", d.getIconName());
				desktopIcon.setStringProperty("Desktop Entry", "Icon", d.getIconPath());
				desktopIcon.setStringProperty("Desktop Entry", "Path", d.getWorkingPath());
				desktopIcon.setStringProperty("Desktop Entry", "StartupNotify", "false");
				desktopIcon.setStringProperty("Desktop Entry", "Terminal", "false");
				desktopIcon.setStringProperty("Desktop Entry", "TerminalOptions", "");
				desktopIcon.setStringProperty("Desktop Entry", "Type", "Application");
				break;
			/* Please help fill in the following */
			case OSX: 	// Move down
			default:
				Main.printDebug("Creation of Desktop icon failed");	// Modified
				//default: System.err.println("Creation of Desktop icon failed");
				return false;
		}
		Main.printDebug("successful.");				// Modified
		//System.out.println("Successful");
		desktopIcon.updateFile();
		return true;
	}
	
	/* 
	 * Copies a file out of the jar to a physical location.  
	 *    Doesn't need to be private, uses a resource stream, so may have
	 *    security errors if ran from webstart application 
	 */
	
	// Modified (moved to Utils)
	 /*
	public static boolean copyFromJar(String sResource, File fDest) {
		if (sResource == null || fDest == null) return false;
		InputStream sIn = null;
		OutputStream sOut = null;
		File sFile = null;
		try {
			fDest.getParentFile().mkdirs();
			sFile = new File(sResource);
		}
		catch(Exception e) {}
		try {
			int nLen = 0;
			sIn = DesktopIconFactory.class.getResourceAsStream(sResource);
			if (sIn == null)
				throw new IOException();
			sOut = new FileOutputStream(fDest);
			byte[] bBuffer = new byte[1024];
			while ((nLen = sIn.read(bBuffer)) > 0)
				sOut.write(bBuffer, 0, nLen);
			sOut.flush();
		}
		catch(IOException ex) {
			ex.printStackTrace();
		}
		finally {
			try {
				if (sIn != null)
					sIn.close();
				if (sOut != null)
					sOut.close();
			}
			catch (IOException eError) {
				eError.printStackTrace();
			}
		}
		return fDest.exists();
	}
	*/
}
